package day05;

import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.co.CoFlatMapFunction;
import org.apache.flink.util.Collector;
import untils.ClickEvent;
import untils.ClickSource;

/**
 *  查询流
 *  第一条流是点击流
 *  另一条是socket流,可以输入要查询名子
 */
public class Example2 {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        //添加点击流
        DataStreamSource<ClickEvent> clickStream = env.addSource(new ClickSource());

        //添加查询流
        DataStreamSource<String> queryStream = env.socketTextStream("hadoop102",9999);

        clickStream.keyBy(r -> r.url)
                //合并两条流,数据类型可以不同
                .connect(queryStream.setParallelism(1).broadcast())
                .flatMap(new Query())
                .print();

        env.execute();
    }

    public static class Query implements CoFlatMapFunction<ClickEvent,String,ClickEvent>{

        private String queryString = "";
        @Override
        public void flatMap1(ClickEvent value, Collector<ClickEvent> out) throws Exception {
            if(value.username.equals(queryString)) out.collect(value);
        }

        @Override
        public void flatMap2(String value, Collector<ClickEvent> out) throws Exception {
            queryString = value;

        }
    }
}
